<?php
#+------------------------------------------------------------------
#| 普通的。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace app\library\websocket\tool;

use app\library\websocket\logic\Users;
use Swoole\WebSocket\Frame;
use think\helper\Str;
use uuid\UUid;

/**
 * 原始消息包
 */
class Package
{
    /**
     * 是否群组消息
     * @var bool
     */
    public $isGroup = 0;
    /**
     * 消息类型
     * @var string
     */
    public $action = '';
    /**
     * 消息内容
     * @var string
     */
    public $data = '';
    /**
     * 会话id(当是群组的时候此参数为)
     * @var string
     */
    public $chatId = '';
    /**
     * 接收人
     * @var string
     */
    public $to = '';
    /**
     * 状态
     * @var int
     */
    public $status = 1;
    /**
     * 撤回
     * @var int
     */
    public $recall = 1;
    /**
     * 发送人
     * @var string
     */
    public $from = '';
    /**
     * 原消息id
     * @var string
     */
    public $msgId = '';
    /**
     * 文件链接或者base字符串
     * @var string
     */
    public $link = '';
    /**
     * 发送消息的时间戳
     * @var string
     */
    public $timestamp = '';
    /**
     * 是否已读
     * @var bool
     */
    public $isRead = 0;

    public function __construct(Frame $frame)
    {
        $this->resetMsgId();
        $message = json_decode($frame->data, true);
        foreach ($message as $key => $value) {
            $property = Str::camel($key);
            $this->$property = $value;
        }
        $this->timestamp = time();
        $this->from = Users::getUserId($frame->fd);
    }

    public function resetMsgId()
    {
        $this->msgId = UUid::create();
        return $this;
    }

    public function __set($property, $value)
    {
        $this->$property = $value;
    }

    public function __get($property)
    {
        if (property_exists($this, $property)) {
            return $this->$property;
        } elseif (isset($this->data[$property])) {
            return $this->data[$property];
        }

        return false;
    }

    public function __toString()
    {
        return json_encode([
            'code'   => 200,
            'notice' => 'success',
            'action' => $this->action,
            'data'   => $this->toArray()
        ], JSON_UNESCAPED_UNICODE);
    }

    public function toArray()
    {
        $propertys = get_class_vars(get_class($this));
        $new = [];
        foreach ($propertys as $key => $value) {
            $new[Str::snake($key)] = $this->$key;
        }
        unset($propertys);
        return $new;
    }
}
